package com.deepexi.sample.controller;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class EsController {

    @Value("${elasticsearch.indexname:tree}")
    private String indexName;
    private String queryField = "title";

    @Autowired
    RestHighLevelClient client;

    @RequestMapping(value = "es/{keyword}")
    public List<String> queryEs(@PathVariable(name = "keyword") String keyword) {
        List<String> list = new ArrayList<>();
        try {
            SearchRequest searchRequest = new SearchRequest(indexName);
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.timeout(new TimeValue(3, TimeUnit.MINUTES));
            sourceBuilder.query(QueryBuilders.termQuery(queryField, keyword));
            searchRequest.source(sourceBuilder);

            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = searchResponse.getHits();
            if (hits.getTotalHits().value == 0L) {
                return list;
            }

            for (SearchHit hit : hits.getHits()) {
                Map<String, Object> sourceMap = hit.getSourceAsMap();
                list.add(sourceMap.get(queryField).toString());
            }

            log.info("queryEs finish");
        } catch (Exception e) {
            log.error("queryEs error:", e);
        }

        return list;
    }


}